<template>
  <PageLayout full :page-style="pageStyle">
    <template #header>
      <HeaderLayout show-back>
        <view>{{ $t('Pairing.PairStep3.Navigator.PairingSuccess.Title') }}</view>
      </HeaderLayout>
    </template>
    <view class="container">
      <image class="srcImg" src="/static/img_PlaceHolder_long.png" v-show="!imgLoad" mode="aspectFit"></image>
      <image class="srcImg" :src="imgUrl" mode="aspectFit" v-show="imgLoad" @load="imgLoaded" @error="imgLoadedFail" />
      <view class="srcText">{{ $t('Pairing.PairStep3.PairSuccess.Title') }}</view>
      <view class="bom">
        <!-- 关注公众号组件 -->
        <view class="official-account" v-if="type != 'TT'">
          <official-account></official-account>
        </view>

        <block v-if="type != 'TT'">
          <ActionButton @click="jumpApplianceDetailPage">{{
            $t('Pairing.PairStep3.StartUse.Button.Text')
          }}</ActionButton>
          <!--跳过（只要有任何设置时都显示）-->
          <button
            class="login loginWhite"
            @click="reLaunch('/pages/navigator/index/index', { current: 0 })"
            style="color: #2d3746; padding-top: 40rpx"
          >
            {{ $t('Pairing.PairStep3.BackHome.Button.Text') }}
          </button>
        </block>
        <block v-else>
          <ActionButton @click="gotoApplianceSetting">
            {{ $t('Pairing.PairStep3.SettingAppliance.Button.Text') }}
          </ActionButton>
          <!--跳过（只要有任何设置时都显示）-->
          <button class="login loginWhite" style="color: #2d3746; padding-top: 40rpx" @click="returnHint">
            {{ $t('Pairing.PairStep3.GoToUse.Button.Text') }}
          </button>
        </block>
      </view>
    </view>
    <view class="successEffect">
      <canvas class="effectCanvas" type="2d" :style="effectStyles"></canvas>
    </view>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'

import { onLoad, onShow } from '@dcloudio/uni-app'
import { getVibInfo } from '@/api/content'
import netconfig from '@/config/netconfig'
import { LaunchEffect } from './successEffect'
import { orderPermanentInfo } from '../../../utils/deviceMessageSubscribe/deviceMessage'
import { reLaunch, showLoading, toPage, toTargetMiniProgramDetailPage } from '@/utils/mpHelper'
import { encryptUserPhone } from '@/api/account'
import { toTargetMiniProgramTypes } from '@/constants/AppInfo'
import { requestSubscribeUsingComplete } from '@/utils/mpHelper'
import type { CSSProperties } from 'vue'
import { useEnvStore } from '@/store/env'
import { useI18n } from 'vue-i18n'
import { getSimpleApplianceList } from '@/api/afterService'
import { useApplianceStore } from '@/store/appliance'
import type { ApplianceData } from '@/types/appliance'

const i18n = useI18n()

let brand: string
let vib: string
let haId: string
let applianceName: string
const pageStyle = {
  backgroundColor: '#fff',
}
const envStore = useEnvStore()

const imgUrl = ref('')
const type = ref('')
const imgLoad = ref(false)
onLoad((options: any) => {
  console.log('onLoad', options)
  const pairingApplianceSubType = options.pairingApplianceSubType
  brand = options.applianceBrand
  type.value = options.type
  haId = options.haId
  vib = options.vib

  if (pairingApplianceSubType != 'SMM') {
    if (haId) {
      let list = haId.split('-')
      if (list.length > 0) {
        brand = list[0]
        vib = list[1]
      }
    }
  }
  // getVibInfo(vib, true).then((res) => {
  //   if (res.code == 0) {
  //     console.info('getVibInfo', res.data, netconfig.ASSETSPRE + res.data.photo)
  //     imgUrl.value = netconfig.ASSETSPRE + res.data.photo
  //   }
  // })
  imgUrl.value = `${netconfig.PHOTO_IMAGE}${vib}/${vib}.png`
})
onShow(() => {
  showSuccessEffect()
})
async function jumpApplianceDetailPage() {
  try {
    // 永久消息订阅
    await orderPermanentInfo(haId)
  } finally {
    jumpApplianceDetail()
  }
}
function imgLoaded() {
  imgLoad.value = true
}
function imgLoadedFail() {
  imgLoad.value = false
}

/**
 * 显示成功动画
 */
const currentInstance = getCurrentInstance()
const effectStyles = ref<CSSProperties>({})
function showSuccessEffect() {
  const { screenWidth, screenHeight } = envStore.systemInfo

  uni
    .createSelectorQuery()
    .in(currentInstance)
    .select('.successEffect .effectCanvas')
    .node(() => {})
    .exec(([query]) => {
      const { node: canvas } = query
      // 初始化
      const ctx = canvas.getContext('2d')
      const width = screenWidth
      const height = screenHeight
      canvas.width = width
      canvas.height = height
      // ctx.scale(pixelRatio, pixelRatio)
      ctx.clearRect(0, 0, width, height)
      effectStyles.value = {
        width: `${width}px`,
        height: `${height}px`,
      }
      _renderConfetti(canvas)
    })
}
function _renderConfetti(canvas: any) {
  /**
   * 发射
   */
  uni
    .createSelectorQuery()
    .in(currentInstance)
    .select('.bom')
    .boundingClientRect((startRect: any) => {
      LaunchEffect(canvas, {
        startRect: startRect as UniNamespace.NodeInfo,
      })
    })
    .exec()
}

// 跳转家电详情页
async function jumpApplianceDetail() {
  // 判断是否需要跳转到其他小程序
  const isOtherMPTypes = toTargetMiniProgramTypes.includes(type.value)
  // 跳转到其他小程序
  if (isOtherMPTypes) {
    // 获取加密小程序用户手机号信息
    const res = await encryptUserPhone()
    const params = {
      haid: haId,
      vib: vib,
      brand: brand,
      sign: res.data.sign,
      phoneData: res.data.encryptDate,
      appliance_type: type.value,
    }
    await toTargetMiniProgramDetailPage(type.value, params, 'Pairing.Finish.LandingPage')
  } else {
    const applianceStore = useApplianceStore()
    await applianceStore.loadList(true)
    applianceStore.setCurrent(haId)

    if (['Freezer', 'Refrigerator'].includes(type.value)) {
      type.value = 'FridgeFreezer'
    }
    let pageUrl = '/pages/appliance/'
    reLaunch(pageUrl + type.value + '/' + type.value, {
      vib: vib,
      brand: brand.toUpperCase(),
      haId: haId,
      type: type.value,
    })
  }
}
function gotoApplianceSetting() {
  showLoading(async () => {
    try {
      // 一次性消息订阅
      await requestSubscribeUsingComplete([netconfig.DeviceStateId])
    } finally {
      const applianceStore = useApplianceStore()
      await applianceStore.loadList(true)
      applianceStore.setCurrent(haId)

      let res = await getSimpleApplianceList()
      if (res.code === 0) {
        let applianceList = res.data || []
        applianceList.forEach((item) => {
          if (item.haId == haId) {
            applianceName = item.name
          }
        })
      }
      let pageUrl = '/pages/appliance/settings/applianceSettings'

      reLaunch(pageUrl, {
        haId: haId,
        vib: vib,
        type: type.value,
        brand: brand,
        name: applianceName ? applianceName : type.value,
        isVirtual: false,
        guest: false,
        connected: true,
        remoteControl: true,
        remoteStart: true,
      })
    }
  })
}
function returnHint() {
  uni.showModal({
    title: i18n.t('Pairstep3.GoExperience.Dialog.Title'),
    content: i18n.t('Pairstep3.GoExperience.Dialog.Content.Text'),
    showCancel: false,
    complete: () => {
      jumpApplianceDetailPage()
    },
  })
}
</script>

<style lang="less">
.sucTitle {
  position: relative;
  margin-left: -20rpx;
  top: 0;
  left: 0;
  width: auto;
  height: 120rpx;
  line-height: 102rpx;
  text-align: center;
}

.progress {
  position: relative;
  width: 100%;
  top: -80rpx;
  color: #4475d5;
  font-size: 32rpx;
}

.sucIcon {
  display: inline-block;
  position: relative;
  vertical-align: middle;
  top: 0;
  left: 0;
  margin: -3rpx 10rpx 0 0;
  width: 36rpx;
  height: 36rpx;
}

.sucDes {
  display: inline-block;
  width: 100%;
  font-size: 32rpx;
  color: #4475d5;
  text-align: center;
}

.desTitle {
  font-size: 28rpx;
  color: #656b7b;
  text-align: center;
}

.questionIcon {
  position: absolute;
  top: 8rpx;
  left: 10rpx;
  width: 24rpx;
  height: 24rpx;
}

.srcImg {
  margin-top: 160rpx;
  width: 520rpx;
  height: 520rpx;
}

.srcText {
  font-family: PingFang SC;
  font-size: 36rpx;
  font-weight: 500;
  color: var(--dack-color);
  margin-top: 60rpx;
}

.content {
  width: 80%;
  padding: 20rpx 0 40rpx 0;
}

.lineContent {
  font-size: 32rpx;
  color: #131b35;
  line-height: 60rpx;
}

.icon {
  display: inline-block;
  margin: 0 10rpx;
  vertical-align: middle;
  width: 52rpx !important;
  height: 40rpx !important;
}

.bom {
  position: absolute;
  width: 100%;
  height: auto;
  bottom: 8%;
  box-sizing: border-box;
  padding: 0 32rpx;
  font-weight: 600;
  z-index: 10;
}

.checkStep {
  display: inline-block;
  position: relative;
  margin-bottom: 20rpx;
  margin-left: -22rpx;
  left: 50%;
  transform: translate(-50%, 0);
  width: auto;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
}

.check {
  display: inline-block;
  margin-top: -8rpx;
  margin-right: 10rpx;
  position: relative;
  vertical-align: middle;
  width: 40rpx;
  height: 40rpx;
}

.checkIcon {
  position: absolute;
  top: 0;
  left: 0;
  width: 40rpx;
  height: 40rpx;
}

.checkBg {
  position: absolute;
  top: 6rpx;
  left: 0;
  width: 36rpx;
  height: 36rpx;
}

.checkText {
  display: inline-block;
  font-size: 32rpx;
}

.login {
  position: relative;
  top: 0;
  left: 0;
}

.login::after {
  border: none;
}

.loginWhite {
  background-image: none;
  background: #fff;
  color: #131b35;
}

.des {
  font-size: 28rpx;
  color: #656b7b;
  text-align: center;
}

.bomUrl {
  margin-top: 20rpx;
  font-size: 32rpx;
  color: #4a90e2;
  text-align: center;
  text-decoration: underline;
}

.bold {
  font-weight: bold;
}

/*bosch海报框*/
.shareBoxImg {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  box-sizing: border-box;
}

.shareContent {
  padding: 0 60rpx;
  position: relative;
  width: 100%;
  height: auto;
  z-index: 10;
  box-sizing: border-box;
}

.close {
  position: relative;
  margin-left: -4rpx;
  top: 15rpx;
  left: 100%;
  width: 44rpx;
  height: 44rpx;
}

.shareBg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.4;
}

.shareImg {
  width: 100%;
}

.shareButton {
  margin-top: 40rpx;
  width: 100%;
  height: 88rpx;
  text-align: center;
}

.shareConfirm {
  border-radius: 50rpx;
  font-size: 32rpx;
  box-sizing: border-box;
}

.shareConfirm {
  margin-left: 50%;
  transform: translate(-50%, 0);
  width: 315px;
  color: #4475d5;
  background: #fff;
  line-height: 88rpx;
}

.poster {
  width: 630rpx;
  height: 1000rpx;
}

/* 活动留存框*/
.activityView {
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1000000;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
}

.activityViewBg {
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.6);
  position: absolute;
}

.activityShowView {
  width: 630rpx;
  height: 1096rpx;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.activityPictureView {
  width: 630rpx;
  height: 1000rpx;
  position: relative;
}

.posterAC {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.posterPlaceHolder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #ffffff;
  position: absolute;
  top: 0;
  left: 0;
}

.posterPlaceHolder image {
  width: 300rpx;
  height: 300rpx;
}

.activityCloseView {
  width: 56rpx;
  height: 56rpx;
  margin-top: 40rpx;
}

.activityCloseView image {
  width: 100%;
  height: 100%;
}

/*smm洗碗机设置跳过时提示框*/
.smmHintCon {
  margin: 10rpx 0 30rpx;
  padding: 0 60rpx;
  box-sizing: border-box;
  font-size: 32rpx;
  color: #131b35;
}

.successEffect {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1;
}
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  box-sizing: border-box;
}
.official-account {
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 48rpx;
}
@media screen and (max-height: 667px) {
  .srcImg {
    margin-top: 40rpx;
  }
  .official-account {
    margin-bottom: 30rpx;
  }
}
@media screen and (max-height: 736px) {
  .srcImg {
    margin-top: 40rpx;
  }
}
</style>
